package org.micro.rbac.core.valid.validator;

import cn.hutool.core.util.StrUtil;
import com.google.common.base.Enums;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import lombok.extern.slf4j.Slf4j;
import org.micro.rbac.core.valid.EnumConstraint;

/**
 * @author hongsir
 * @apiNote 摘要:枚举类型校验
 * @since 2019-05-29 09:09
 */
@Slf4j
public class EnumConstraintValidator implements ConstraintValidator<EnumConstraint, String> {

    private EnumConstraint enumConstraint;

    @Override
    public void initialize(EnumConstraint enumConstraint) {
        this.enumConstraint = enumConstraint;
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StrUtil.isBlank(value)) {
            return true;
        }
        boolean checkFlag = Enums.getIfPresent(enumConstraint.value(), value).isPresent();
        if (!checkFlag) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(StrUtil.blankToDefault(enumConstraint.message(), "枚举值异常")).addConstraintViolation();
        }
        return checkFlag;
    }
}
